<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      label-position="top"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="loginForm.password"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <img class="code-image" :src="codeImg" alt="" @click="getCodeImg()" />
        <el-input v-model="loginForm.code"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from "@/api/login";
import { getCodeImage } from "@/api/login";

export default {
  name: "LoginView",
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
        code: "",
        key: "",
      },
      codeImg: "",
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
    };
  },
  methods: {
    login() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          // 登录逻辑，可以发送请求到后端进行验证
          console.log("登录key:", this.loginForm.key);
          const res = await login(this.loginForm);
          console.log(res);
          if (res.data.success) {
            this.$store.commit("user/setUserInfo", res.data.result);
            // 登录成功后跳转到首页
            this.$router.push("/index");
          }
        } else {
          console.log("表单验证失败");
        }
      });
    },
    async getCodeImg() {
      console.log("getCodeImg");
      this.getRandomKey();
      const res = await getCodeImage(this.loginForm.key);
      if (res.data.success) {
        this.codeImg = res.data.result;
      }
    },
    getRandomKey() {
      this.loginForm.key = Math.floor(Math.random() * 10000);
    },
  },
  created() {
    this.getCodeImg();
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("@/assets/background.png");
  background-size: cover; /* 让背景图片填满整个容器 */
  background-position: center; /* 将背景图片居中 */
}
.code-image {
  width: 100px;
  height: 50px;
  margin-bottom: 10px;
}
.user-info-item{
    justify-content: flex-start;
}
</style>